#include "alt_up_rs232.h"

int alt_up_rs232_enable_read_interrupt()
{
	alt_u32 ctrl_reg;
	ctrl_reg = IORD_ALT_UP_RS232_CONTROL(IRDA_BASE); 
	// set RE to 1 while maintaining other bits the same
	ctrl_reg |= ALT_UP_RS232_CONTROL_RE_MSK;
	IOWR_ALT_UP_RS232_CONTROL(IRDA_BASE, ctrl_reg);
	return 0;
}

int alt_up_rs232_disable_read_interrupt()
{
	alt_u32 ctrl_reg;
	ctrl_reg = IORD_ALT_UP_RS232_CONTROL(IRDA_BASE); 
	// set RE to 0 while maintaining other bits the same
	ctrl_reg &= ~ALT_UP_RS232_CONTROL_RE_MSK;
	IOWR_ALT_UP_RS232_CONTROL(IRDA_BASE, ctrl_reg);
	return 0;
}

unsigned alt_up_rs232_get_num_chars_in_read_FIFO()
{
	alt_u16 ravail = 0;
	// we can only read the 16 bits for RAVAIL --- a read of DATA will discard the data
	ravail = IORD_16DIRECT(IOADDR_ALT_UP_RS232_DATA(IRDA_BASE), 2); 
	return ravail;
}

unsigned alt_up_rs232_get_num_chars_in_write_FIFO()
{
	alt_u32 ctrl_reg;
	ctrl_reg = IORD_16DIRECT(IRDA_BASE, 1); 
	return (ctrl_reg & ALT_UP_RS232_CONTROL_WSPACE_MSK) >> ALT_UP_RS232_CONTROL_WSPACE_OFST;
}

int alt_up_rs232_check_parity(alt_u32 data_reg)
{
	unsigned parity_error = (data_reg & ALT_UP_RS232_DATA_PE_MSK) >> ALT_UP_RS232_DATA_PE_OFST;
	return (parity_error ? -1 : 0);
}

int alt_up_rs232_write_data(alt_u8 data)
{
	alt_u32 data_reg;
	data_reg = IORD_ALT_UP_RS232_DATA(IRDA_BASE);

	// we can write directly without thinking about other bit fields for this
	// case ONLY, because only DATA field of the data register is writable
	IOWR_ALT_UP_RS232_DATA(IRDA_BASE, (data>>ALT_UP_RS232_DATA_DATA_OFST) & ALT_UP_RS232_DATA_DATA_MSK);
	return 0;
}

int alt_up_rs232_read_data(alt_u8 *data)
{
	alt_u32 data_reg;
	data_reg = IORD_ALT_UP_RS232_DATA(IRDA_BASE);
	*data = (data_reg & ALT_UP_RS232_DATA_DATA_MSK) >> ALT_UP_RS232_DATA_DATA_OFST;
	return alt_up_rs232_check_parity(data_reg);
}


